package com.aliang.book_java1.controller;


import com.aliang.book_java1.po.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
@Api(value = "示例控制器", tags = "登录接口Controller")
public class LoginController {

    /**
     * 登录接口，时间紧急，简单实现（而且为了代码能在面试官那边运行，这里就不采用过多的外部工具类）
     * @param userInfo
     * @param request
     * @param response
     */
    @RequestMapping(value = "/userLogin", method = { RequestMethod.POST })
    @ApiOperation(value = "登录", notes = "这个接口进行登录操作")
    public void userLogin(@RequestBody UserInfo userInfo, HttpServletRequest request,
                          HttpServletResponse response) throws Exception {
        System.out.println("------"+userInfo);
        //校验用户是否存在；
        //校验密码是否正确
        //密码这边需要加密，这边简写就不加密了

        // 这里只是简单地模拟验证，实际中应该查询数据库
        if ("user".equals(userInfo.getUserName()) && "password".equals(userInfo.getPassword())) {
            // 验证成功，将用户名存入Session
            HttpSession session = request.getSession();
            //这里也可以生成sessionid返回浏览器，但是我这边没有做前端页面，所以就不返回了
            session.setAttribute("username", userInfo.getUserName());

            // 重定向到受保护的页面
            //response.sendRedirect("这里填写具体页面");
        } else {
            // 验证失败，重定向回登录页面
            request.setAttribute("error", "Invalid username or password");
            RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
            dispatcher.forward(request, response);
        }




    }


}
